package huixue.cn.com.rxapp.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import huixue.cn.com.rxapp.R;

/**
 * Created by gongdongyang 2019/7/14
 * Describe:
 */
public class MeshView extends View {

    private int Hieght = 200;

    private int Width = 200;

    private int Count = (Hieght+1)*(Width+1);

    private float []origins = new float [Count*2];
    private float []verts = new float [Count*2];

    private Bitmap bitmap;

    private float K = 1;


    public MeshView(Context context) {
        this(context,null);
    }

    public MeshView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public MeshView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setLayerType(LAYER_TYPE_SOFTWARE,null);
        initView();
    }

    private void initView(){
        bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.timg);
        for(int i = 0;i<Hieght+1;i++){
            for(int j = 0;j<Width+1;j++){
                float fx = ((float) bitmap.getWidth() * j)/Width;
                float fy = ((float) bitmap.getHeight() * i)/Hieght;
                verts[(i*(Width+1)+j)*2+0] = origins[(i*(Width+1)+j)*2+0] = fx+100;
                verts[(i*(Width+1)+j)*2+1]  = origins[(i*(Width+1)+j)*2+1] = fy+200;
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //super.onDraw(canvas);
        for(int i = 0;i<Hieght+1;i++) {
            for (int j = 0; j < Width + 1; j++) {
                verts[(i*(Width+1)+j)*2+0] = origins[(i*(Width+1)+j)*2+0];
                float offsetY = (float) Math.sin((float)j/Width*2*Math.PI+K*2+Math.PI);

                verts[(i*(Width+1)+j)*2+1] = origins[(i*(Width+1)+j)*2+1] + offsetY *50;
            }
        }
        K +=0.1;
        canvas.drawBitmapMesh(bitmap,Width,Hieght,verts,0,null,0,null);
        postInvalidate();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }
}
